/**
 *Copyright(c) HNA SYSTEMS Co., LTD
 *
 *@date 2013-7-18
 * 	
 *Original Author: 郑兴(zhengxing)
 *
 *ChangeLog
 *
 */
package com.hnas.sys.core.spring;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import com.hnas.sys.core.util.CacheUtil;
import com.hnas.sys.domain.ResourceStatus;

/**
 * @author 郑兴(zhengxing)
 *
 */
public class DTAccessDecisionManager implements AccessDecisionManager {

	/* (non-Javadoc)
	 * @see org.springframework.security.access.AccessDecisionManager#decide(org.springframework.security.core.Authentication, java.lang.Object, java.util.Collection)
	 */
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		
		if( configAttributes == null ) {
			return;
		}
		Iterator<ConfigAttribute> ite = configAttributes.iterator();
		Map<String, ResourceStatus> authorityStatus = CacheUtil.getAuthorityStatusMap();
		while( ite.hasNext()){
			ConfigAttribute ca = ite.next();
			String needAuthority = ((SecurityConfig)ca).getAttribute();
			//grantedAuthority 为用户所被赋予的权限。 needRole 为访问相应的资源应该具有的权限。
			for( GrantedAuthority grantedAuthority: authentication.getAuthorities()){
				if(needAuthority.trim().equals(grantedAuthority.getAuthority().trim())){
					if(null == authorityStatus.get(needAuthority) || authorityStatus.get(needAuthority) == ResourceStatus.VALID) {
						return;
					}
				}
			}
		}
		
		/*throw new AccessDeniedException("no authority...");*/
	}

	/* (non-Javadoc)
	 * @see org.springframework.security.access.AccessDecisionManager#supports(org.springframework.security.access.ConfigAttribute)
	 */
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	/* (non-Javadoc)
	 * @see org.springframework.security.access.AccessDecisionManager#supports(java.lang.Class)
	 */
	public boolean supports(Class<?> clazz) {
		return true;
	}

}
